//
//  LAB_FiltersViewController.m
//  Camera
//
//  Created by Bodi on 16/8/15.
//  Copyright © 2016年 葛海一. All rights reserved.
//

#import "LAB_FiltersViewController.h"
#import "LAB_Filters.h"
#import "LAB_SaveViewController.h"
#import "LAB_GestureImageView.h"
#import "LAB_Stick.h"
#import "LAB_AdjustView.h"
#import <CoreImage/CoreImage.h>
@interface LAB_FiltersViewController ()<LABFootViewDelegate>
@property (nonatomic, retain)NSString *string;
@property (nonatomic, retain)LAB_GestureImageView *gesture;
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, retain)UIView  *bodiView;
@property (nonatomic, retain)LAB_Stick *stick;

@property (nonatomic, retain)LAB_AdjustView *adView;
@property (nonatomic, retain)LAB_AdjustView *conView;

@property (nonatomic, retain)NSString *str1;
@property (nonatomic, retain)NSString *str2;

@property (nonatomic, retain)UIImage *image;

@property (nonatomic, retain)NSMutableArray *array;

@property (nonatomic, assign)CGFloat alp;


@property (nonatomic, retain)UILabel *label;
@property (nonatomic, retain)UILabel *label1;

@property (nonatomic, retain) NSMutableArray<LAB_Stick *> *stickArray;

//原始图
@property (nonatomic, retain)UIImageView *originalImage;


@end

@implementation LAB_FiltersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //对比按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(WIDTH-60, WIDTH + 55, 30, 30);
//    button.backgroundColor = [UIColor cyanColor];
    [button setImage:[UIImage imageNamed:@"查看原图"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(original:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(original1:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.array = [NSMutableArray array];
    [self setFiltersControllerUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFilter:) name:@"fitlerName" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stic:) name:@"trigger" object:self.string];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(location:) name:@"location" object:self.string];

    
    self.stickArray = [NSMutableArray array];
    
    //    self.bodiView = [[UIView alloc]initWithFrame:CGRectMake(0, 50, WIDTH, WIDTH)];
//    [self.view addSubview:self.bodiView];
    
        
}

//对比
- (void)original:(UIButton *)button{
    self.originalImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 50, WIDTH, WIDTH)];
    self.originalImage.image = self.filtersImg;
    self.originalImage.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.originalImage];

    
    [self.view bringSubviewToFront:self.originalImage];
//   NSLog(@"%@", self.originalImage);
}
- (void)original1:(UIButton *)button{
    [self.originalImage removeFromSuperview];

}

- (void)location:(NSNotification *)noti{
    self.str1 = noti.object[0];
    self.str2 = noti.object[1];
    
    [self add];
    

}

- (void)add{
//    NSMutableArray *imioArray = [NSMutableArray array];
//    [imioArray addObject:self.stick.gesView.image];
//    [imioArray addObject:self.str1];
//    [imioArray addObject:self.str2];
//    
//    [self.array addObject:imioArray];
//    
//    for (int i = 0; i < self.array.count - 1; i++) {
//        if (self.array[i + 1][0] == self.array[i][0]) {
//            [self.array removeObjectAtIndex:i];
//        }
//    }
//    
//    
//    NSLog(@"%@", self.array);



}


- (void)stic:(NSNotification *)noti{
       self.string = noti.object;
//        self.gesture = [[LAB_GestureImageView alloc]initWithImage:[UIImage imageNamed:self.string] withFrame:CGRectMake(100, 300, 100, 100)];
//        [self.view addSubview:_gesture];
    self.stick = [[LAB_Stick alloc]initWithFrame:CGRectMake(0, 50, 100, 100) string:self.string];
    [self.stickArray addObject:_stick];
    [self.filtersImageView addSubview:_stick];
//    CGFloat s1 = self.str1.floatValue;
//    CGFloat s2 = self.str2.floatValue;
//    
//    CGSize finalSize = [self.filtersImg size];
//    CGSize hatSize = [self.stick.gesView.image size];
//    UIGraphicsBeginImageContext(finalSize);
//    [self.filtersImg drawInRect:CGRectMake(0,0,finalSize.width,finalSize.height)];
//    [self.stick.gesView.image drawInRect:CGRectMake(s1 * 4,s2 * 4,100 * 4,100 * 4)];
//    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    self.image = [[UIImage alloc]init];
//    self.image = newImage;
//
//    self.filtersImageView.image = newImage;
//    NSLog(@"aaaaa%@", newImage);
//
    
    
   
    self.image = [[UIImage alloc]init];
    self.image = self.stick.gesView.image;
    
    
    
//    NSMutableArray *imioArray = [NSMutableArray array];
//    [imioArray addObject:self.stick.gesView.image];
//    [imioArray addObject:self.str1];
//    [imioArray addObject:self.str2];
//    
//    [self.array addObject:imioArray];
//    
//    NSLog(@"%@", self.array);

    
    

}
- (void)changeFilter:(NSNotification *)filterName{
    UIImage * showFilterImage = [[LAB_Filters alloc]initWithImage:self.filtersImg filterName:[filterName object]].filterImg;
    self.filtersImageView.image = showFilterImage;

}
#pragma mark - 设置顶部导航栏
- (void)setNaViewUI{
    [self addNavViewTitle:@"工具"];
    [self addBackButton];
    [self addNextButton];
    [self.nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];


}
#pragma mark 继续按钮的点击事件
- (void)nextBtnClick{
    LAB_SaveViewController *saveVC = [[LAB_SaveViewController alloc]init];
    saveVC.doneImageView.image = self.filtersImageView.image;

    
    
    for (int i = 0; i < self.stickArray.count; i++) {
        self.stickArray[i].button.hidden = YES;
        if ([self.stickArray[i].gesView isAnimating]) {
            [self.stickArray[i].gesView stopAnimating];
            self.stickArray[i].gesView.image = self.stickArray[i].imageArr[0];
        }
    }
    
    
    
    
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    
    
    UIGraphicsBeginImageContextWithOptions(_filtersImageView.bounds.size, NO, [UIScreen mainScreen].scale);
    [_filtersImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    saveVC.doneImageView.image  = image;
    [self.navigationController pushViewController:saveVC animated:YES];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    for (int i = 0; i < self.stickArray.count; i++) {
        if (self.stickArray[i].imageArr) {
            self.stickArray[i].gesView.animationImages = self.stickArray[i].imageArr;
            self.stickArray[i].gesView.animationDuration = 0.15 * self.stickArray[i].imageArr.count;
            self.stickArray[i].gesView.animationRepeatCount = 0;
            [self.stickArray[i].gesView startAnimating];
        }
    }
}

#pragma mark - 设置视图UI
- (void)setFiltersControllerUI{
    [self setNaViewUI];
    self.filtersImageView.image = self.filtersImg;
    [self.view addSubview:self.filtersImageView];
    [self.view addSubview:self.footView];
    [self.view addSubview:self.dynamicStickersView];

}

- (LAB_FootView *)footView{
    if (!_footView) {
        _footView = [[LAB_FootView alloc] initWithFrame:CGRectMake(0, HEIGHT - 50, WIDTH, 50)];
        NSArray *titleArr = [[NSArray alloc] initWithObjects:@"动态贴纸",@"调整",@"贴纸",@"滤镜", nil];
        _footView.backgroundColor = [UIColor blackColor];
        _footView.titleArr = titleArr;
        [_footView addFootViewButton];
        _footView.delegate = self;
    }
    return _footView;
}
- (void)buttonDidSeletedWithIndex:(NSInteger)index{
    if (index == 3) {
        if (_stickersView) {
            _stickersView.hidden = YES;
                    }
        _adView.hidden = YES;
        _conView.hidden = YES;
        _label.hidden = YES;
        _label1.hidden = YES;
        _filtersView.hidden = NO;
        _dynamicStickersView.hidden = YES;
        [self.view addSubview:self.filtersView];
    }
    if (index == 2) {
        if (_stickersView) {
            _stickersView.hidden = NO;
        }
        _adView.hidden = YES;
        _conView.hidden = YES;
        _label.hidden = YES;
        _label1.hidden = YES;
        _dynamicStickersView.hidden = YES;
        [self.view addSubview:self.stickersView];
    }
    
    if (index == 1) {
         _stickersView.hidden = YES;
        _filtersView.hidden = YES;
        _conView.hidden = NO;
        _adView.hidden = NO;
        _label.hidden = NO;
        _label1.hidden = NO;
       _dynamicStickersView.hidden = YES;
        [self.view addSubview:self.adView];
        [self.view addSubview:self.conView];
    }
    if (index == 0){
        //        NSLog(@"打开视图 === %zi", index);
        //        [self.filtersView removeFromSuperview];
        
        _stickersView.hidden = YES;
        _filtersView.hidden = YES;
        _conView.hidden = YES;
        _adView.hidden = YES;
        _label.hidden = YES;
        _label1.hidden = YES;
        _dynamicStickersView.hidden = NO;
        
    }
//    else{
//        NSLog(@"打开视图 === %zi", index);
//        [self.filtersView removeFromSuperview];
//    }

}
#pragma mark - 处理图片的视图
- (UIImageView *)filtersImageView{
    if (!_filtersImageView) {
        _filtersImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, WIDTH, WIDTH)];
        
        
//        CGSize finalSize = [self.filtersImg size];
//        CGSize hatSize = [self.stick.image size];
//        UIGraphicsBeginImageContext(finalSize);
//        [self.filtersImg drawInRect:CGRectMake(0,0,finalSize.width,finalSize.height)];
//        [self.stick.image drawInRect:CGRectMake(0,0,hatSize.width,hatSize.height)];
//        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//       
//        _filtersImageView.image = newImage;
//        NSLog(@"aaaaa%@", newImage);
        
        _filtersImageView.userInteractionEnabled = YES;
        
    }
    return _filtersImageView;
}
#pragma mark - 滤镜视图
- (LAB_FiltersView *)filtersView{
//    self.stickersView.hidden = YES;
    if (!_filtersView) {
        _filtersView = [[LAB_FiltersView alloc] initWithFrame:CGRectMake(0, HEIGHT - 155, WIDTH, 120)];
    }
    return _filtersView;

}
#pragma mark - 贴纸视图
- (LAB_StickersView *)stickersView{
    
    if (!_stickersView) {
//        self.stickersView.hidden = NO;
        _stickersView = [[LAB_StickersView alloc]initWithFrame:CGRectMake(0, HEIGHT - 155, WIDTH, 120)];
    }
    return _stickersView;
}

#pragma mark - 调整视图
- (LAB_AdjustView *)adView{
    if (!_adView) {
       self.label = [[UILabel alloc]initWithFrame:CGRectMake(10, HEIGHT - 170, 60, 50)];
         self.label.text = @"饱和度";
        [self.view addSubview:_label];
        _adView = [[LAB_AdjustView alloc]initWithFrame:CGRectMake(80, HEIGHT - 170, WIDTH - 100, 50)];
        _adView.value = 0.5;
        [self.adView addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        
      

    }
    
    return _adView;

}

- (GHY_DynamicStickersView *)dynamicStickersView{
    
    if (!_dynamicStickersView) {
        _dynamicStickersView = [[GHY_DynamicStickersView alloc] initWithFrame:CGRectMake(0, HEIGHT - 155, WIDTH, 120)];
        
        __weak LAB_FiltersViewController *vc = self;
        
        _dynamicStickersView.selectedCell = ^(NSArray<UIImage *> *imageArr){
            
            vc.stick = [[LAB_Stick alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
            vc.stick.imageArr = imageArr;
            [vc.filtersImageView addSubview:vc.stick];
            [vc.stickArray addObject:vc.stick];
        };
        
        
        
    }
    
    return _dynamicStickersView;
    
}

-(LAB_AdjustView *)conView{
    if (!_conView) {
        self.label1 = [[UILabel alloc]initWithFrame:CGRectMake(10, HEIGHT - 120, 60, 50)];
        self.label1.text = @"对比度";
        [self.view addSubview:_label1];
        _conView = [[LAB_AdjustView alloc]initWithFrame:CGRectMake(80, HEIGHT - 120, WIDTH - 100, 50)];
        _conView.value = 0.3;
        [self.conView addTarget:self action:@selector(sliderCon:) forControlEvents:UIControlEventValueChanged];

    }
    return _conView;


}

-(void)sliderAction:(LAB_AdjustView *)HS
{
//    NSLog(@"%f", HS.value);
//   self.filtersImageView.alpha = 1 - HS.value  + 0.3;
//    self.alp = self.filtersImageView.alpha;
    
    CIImage *beginImage = [CIImage imageWithCGImage:self.filtersImg.CGImage];
    CIFilter * filter = [CIFilter filterWithName:@"CIColorControls"];
    [filter setValue:beginImage forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithFloat: HS.value * 2 ] forKey:@"inputSaturation"];
//    NSLog(@"%f", HS.value * 2);
    // 得到过滤后的图片
    CIImage *outputImage = [filter outputImage];
    // 转换图片, 创建基于GPU的CIContext对象
    CIContext *context = [CIContext contextWithOptions: nil];
    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *newImg = [UIImage imageWithCGImage:cgimg];
    
    
    self.filtersImageView.image = newImg;
    // 释放C对象
    CGImageRelease(cgimg);

    
}

- (void)sliderCon:(LAB_AdjustView *)HS{

//    CIContext *context = [CIContext contextWithOptions:nil];
//    CIImage *superImage = [CIImage imageWithCGImage:self.filtersImg.CGImage];
//    CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
//    [lighten setValue:superImage forKey:kCIInputImageKey];
//    [lighten setValue:@(0.8) forKey:@"inputBrightness"];
//    CIImage *result = [lighten valueForKey:kCIOutputImageKey];
//    CGImageRef cgImage = [context createCGImage:result fromRect:[superImage extent]];
//    self.filtersImg = [UIImage imageWithCGImage:cgImage];
    CGFloat d = 2 - HS.value;
    CIImage *beginImage = [CIImage imageWithCGImage:self.filtersImg.CGImage];
    CIFilter * filter = [CIFilter filterWithName:@"CIColorControls"];
    [filter setValue:beginImage forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithFloat: HS.value * 4 ] forKey:@"inputContrast"];
//    NSLog(@"%f", HS.value * 4);
    // 得到过滤后的图片
    CIImage *outputImage = [filter outputImage];
    // 转换图片, 创建基于GPU的CIContext对象
    CIContext *context = [CIContext contextWithOptions: nil];
    CGImageRef cgimg = [context createCGImage:outputImage fromRect:[outputImage extent]];
    UIImage *newImg = [UIImage imageWithCGImage:cgimg];
    
    
    self.filtersImageView.image = newImg;
    // 释放C对象
    CGImageRelease(cgimg);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
